<template>
  <div class="book-cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="cart-header">
          <h3>我的结算</h3>
        </div>
      </template>
      <div class="address-container">
        <el-button class="add-btn" style="background-color: #ff7d00">收货地址</el-button>
        <!-- 下拉框 -->
        <el-select v-model="selectedAddress" placeholder="请选择地址" class="address-select">
<!--          <option value="" disabled selected>请选择地址</option>-->
          <!-- 可在此处动态添加地址选项 -->
          <el-option
              v-for="(address,index) in addressList"
              :key="address.id"
              :value="address.id"
              :label="address.addressData"
          >
          </el-option>
        </el-select>

        <!-- 新增地址按钮-卡片 -->
<!--        <el-button class="add-btn" @click="newAddress">新增地址</el-button>-->
        <!-- 新增地址按钮-弹窗 -->
        <el-button class="add-btn" @click="newDia">新增地址</el-button>

      </div>

<!--      主页面-->
      <el-table
          :data="cartItems"
          stripe
          border
          class="cart-table"
          style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="书名" min-width="180"></el-table-column>
        <el-table-column label="图片" width="120" align="center">
          <template #default="scope">
            <img :src="$urlImage+scope.row.image" alt="书籍封面" class="book-image">
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(￥)" width="100" align="center">
          <template #default="scope">
            {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="160" align="center">
          <template #default="scope">
            {{ scope.row.quantity }}
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="金额(￥)" width="100" align="center">
          <template #default="scope">
            {{ scope.row.sum.toFixed(2) }}
          </template>
        </el-table-column>

      </el-table>

      <div class="cart-footer">
        <div class="left-section">
<!--          <el-button-->
<!--              type="text"-->
<!--              @click="clearCart"-->
<!--              class="clear-cart-btn">-->
<!--            <i class="el-icon-delete"></i> 清空购物车-->
<!--          </el-button>-->
        </div>

        <div class="right-section">
          <div class="summary-info">
            共有 <span class="highlight">{{ totalQuantity }}</span> 本书，
            合计 <span class="highlight">￥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <el-button
              type="primary"
              size="medium"
              :disabled="disabled"
              class="checkout-btn"
              @click="checkout">
            提交订单
          </el-button>
        </div>
      </div>
    </el-card>
  </div>

  <NewAddressDia :dialogVisible="dialogVisible" @visible="getVisible" @reloadAddress="refreshAddress"></NewAddressDia>

</template>

<script setup>
import {ref, computed, onMounted, reactive} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import { userStore } from '@/store/index.js'
import router from "@/router/index.js";
import NewAddressDia from "@/components/NewAddressDia.vue";
const userItemStore = userStore();
//新增地址-弹窗
const dialogVisible=ref(false);
const newDia=()=>{
  dialogVisible.value=true;
}
const getVisible=(val)=>{
  dialogVisible.value=val;
}
const refreshAddress=()=>{
  initAddress();
}


//新增地址-卡片
const newAddress=()=>{
  router.push("/newAddress").catch(error => error);
}

//获取地址信息
const addressList=ref([]);
const selectedAddress=ref(null)
const initAddress=()=>{
  axios.get(`/address/getAddressByUid/${userItemStore.user.id}`).then(resp=>{
    addressList.value=resp.data;
    addressList.value.forEach((item)=>{
      if (item.isDefault===1){
        selectedAddress.value=item.id;
      }
    })
  })
}

// 购物车数据
const cartItems = ref([])


//购物车信息初始化；
const initData=()=>{
  axios.post(`/cart/getCartList/${userItemStore.user.id}`).then((resp)=>{
    cartItems.value =Object.values(resp.data.items);
    totalQuantity.value = resp.data.amount;
    totalAmount.value = resp.data.totalPrice;
  })
}


// 计算属性：总数量
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算属性：总金额
const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.sum, 0)
})


// 结算
const uniqueCode = ref('')     //唯一标识
const disabled = ref(false)    //提交按钮不可用
const mounted = ()=> {
  //创建提交的唯一标识
  uniqueCode.value = "WNXY_" + Date.now();
  console.log("提交订单，唯一标识：" + this.uniqueCode);
}

const checkout = () => {
  if(!selectedAddress.value){
    return ElMessage.warning("请选择收货地址")
  }

  disabled.value = true;

  //5秒后可点击
  setTimeout(() => {
    disabled.value = false;
  }, 5000);

  axios.post(`/order/addNewOrder/${userItemStore.user.id}`,{
    uniqueCode: uniqueCode.value,
    addressId: selectedAddress.value
  }).then((resp)=>{
    ElMessage.success(resp.data);
    //过2秒后再跳转
    setTimeout(() => {
      //跳转到订单列表页面
      router.push('/myOrder').catch(error => error);
    }, 1000);
  }).catch(error=>{
    ElMessage.error(error.response.data);
  })
  
}


// 组件挂载后执行
onMounted(() => {
  // 可以在这里添加初始化逻辑，比如从本地存储加载购物车数据
  initData();
  initAddress();
})
</script>

<style scoped>


.address-container {
  display: flex;
  align-items: center;
  gap: 10px; /* 控制下拉框与按钮间距 */
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
  width: fit-content;
}

/* 下拉框样式 */
.address-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 400px; /* 控制下拉框宽度 */
}

/* 新增按钮样式 */
.add-btn {
  padding: 8px 20px;
  background-color: #4a90e2; /* 蓝色主题色 */
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  width:120px;
}

.add-btn:hover {
  background-color: #357abd; /* 鼠标悬停时加深颜色 */
}


.book-cart-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
  font-weight: bold;
  font-size: 18px;
}

.cart-table {
  margin-top: 20px;
}

.book-image {
  width: 80px;
  height: 112px;
  object-fit: cover;
  border-radius: 4px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebedf0;
}

.left-section {
  flex: 1;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary-info {
  font-size: 16px;
  color: #333;
}

.highlight {
  color: #ff7d00;
  font-weight: bold;
}

.clear-cart-btn {
  color: #909399;
}

.clear-cart-btn:hover {
  color: #ff7d00;
}

.checkout-btn {
  background-color: #ff7d00;
  border-color: #ff7d00;
  padding: 8px 30px;
  font-size: 16px;
  border-radius: 4px;
}

.checkout-btn:hover {
  background-color: #ff9126;
  border-color: #ff9126;
}
</style>